package com.cy.ppj.web.admin.user;

import com.cy.ppj.comm.utils.CommonUtils;
import com.cy.ppj.model.Result;
import com.cy.ppj.model.dto.user.UserImprotDTO;
import com.cy.ppj.service.user.UserService;
import com.cy.ppj.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @description: 后台用户管理
 * @author: Ocean
 * @create: 2018-07-20 14:12
 **/
@Slf4j
@RestController
@RequestMapping("/admin/user")
@Api(tags = "后台-用户管理")
public class AdminUserController extends BaseController {

    @Autowired
    private UserService userService;

    @ApiOperation("批量导入用户")
    @PostMapping("/import/excel")
    public Result improtExcel(@ApiParam(value = "用户名单", required = true) @RequestParam MultipartFile multipartFile){

        Workbook wb = null;
        try {
            if (CommonUtils.isExcel2003(multipartFile.getOriginalFilename())) {
                wb = new HSSFWorkbook(multipartFile.getInputStream());
            } else {
                wb = new XSSFWorkbook(multipartFile.getInputStream());
            }
        } catch (IOException e) {
            log.error("improtExcel error:", e);
            return fail("解析文件异常");
        }
        Sheet sheet = wb.getSheetAt(0);
        List<UserImprotDTO> userImprotDTOList = new ArrayList<>();
        for (int i = 0; i <= sheet.getLastRowNum(); i++) {
            Row row = sheet.getRow(i);
            String mobile = new BigDecimal(row.getCell(0).getNumericCellValue()).toString();
            String name = row.getCell(1).getStringCellValue();
            UserImprotDTO userImprotDTO = new UserImprotDTO();
            userImprotDTO.setMobile(mobile);
            userImprotDTO.setName(name);
            userImprotDTOList.add(userImprotDTO);
        }
        try {
            userService.insertUsers(userImprotDTOList);
        } catch (Exception e) {
            log.error("improtExcel error:", e);
            return fail("导入文件异常");
        }

        return ok();
    }

}
